package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static com.hmdp.utils.RedisConstants.LOGIN_TYPE_LIST;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //1.查询redis是否有这数据
        String loginTypeList = stringRedisTemplate.opsForValue().get(LOGIN_TYPE_LIST);
        //2.缓存内有数据，直接返回
        if (StrUtil.isNotBlank(loginTypeList)) {
            List<ShopType> LoginTypelist = JSONUtil.toList(loginTypeList, ShopType.class);
            return Result.ok(LoginTypelist);
        }
        //3.缓存内没数据，数据库查询
        List<ShopType> typeList = typeService.query().orderByAsc("sort").list();

        //4.数据库查询没有数据，返回失败
        if(typeList==null){
            return Result.fail("类型获取失败");
        }
        //5.数据库查询有数据，保存到缓存中
        stringRedisTemplate.opsForValue().set(LOGIN_TYPE_LIST,JSONUtil.toJsonStr(typeList));
        //6.返回数据
        return Result.ok(typeList);
    }
}
